<?php
include_once("CSS.class.php");
include_once("JS.class.php");
include_once("EventManager.class.php");

class Row
{
	var $elements = array();
	var $ID;
	var $events;
	var $css;
	var $js;
	var $cantCols  = 0;
	var $__maxCols = 0;
	var $template = "\n\n<tr{params}>{inputs}</tr>\n";
	var $isValid = true;
	var $hasFile = false;

	function Row($id)
	{
		$this->css = new CSS;
		$this->js  = new JS($this);
		$this->events = new EventManager;

		$this->ID = $id;
	}

	function add($element)
	{
		if (get_class($element) == 'file')
		{
			$this->hasFile = true;
		}
		$this->elements[$element->ID] = $element;
		if (empty($element->label))
		{
			$this->template['label'] = '';
			$this->cantCols++;
		} else {
			$this->cantCols += 2;
		}

		if ($this->isValid)
		{
			$this->isValid = $this->isValid && $element->isValid();
		}
	}

	function remove($element)
	{
		unset($this->elements[$element->ID]);
		$this->cantCols--;

		if (!$element->isValid())
		{
			$this->__reCheckIsValid();
		}
	}

	function __reCheckIsValid()
	{
		$this->isValid = true;
		foreach($this->elements as $element)
		{
			if ($this->isValid)
			{
				$this->isValid = $this->isValid && $element->isValid();
			} else {
				break;
			}
		}
	}

	function addText($txt)
	{
		$text = new StaticText($txt);
		$text->ID = "static";

		$this->add($text);
	}

	function getCSS()
	{
		return $this->css->getClass() . $this->css->getStyles();
	}

	function getID()
	{
		return $this->ID;
	}

	function getEvents()
	{
		return $this->events->getEvents();
	}

	function getHTML()
	{
		$inputs = "";
		if (!empty($this->elements))
		{
			$i    = 0;
			foreach($this->elements as $ID => $element)
			{
				$i += (empty($element->label) ? 1 : 2);
				$colspan = 0;
				if ($this->cantCols == $i)
				{
					if ($this->__maxCols > $this->cantCols)
					{
						$colspan = ($this->__maxCols - $this->cantCols + 1);
					}
				}
				$element->colspan = $colspan;
				$inputs .= $element->getHTML();
			}
		}

		$params = $this->getCSS() . $this->getEvents();

		$ret = str_replace(array('{params}', '{inputs}'), array($params, $inputs), $this->template);
		return $ret;
	}

	function isValid()
	{
		return $this->isValid;
	}

	function getFirstID()
	{
		$elements = array_values($this->elements);
		$elem     = $elements[0];

		return $elem->ID;
	}
}

?>